[Golang] gorm 2.0 insert on duplicate update


Posted by kitecloud213 on 2020-09-09

最近升級了 gorm 2.0,紀錄一下 on duplicate update 寫法

type TableItem struct {
    ID int // PK
    Amount int
}

func Create(ID int, amount int) error {
    db := dbPool.Get() // 取得已經建立好的 connection
    item := &TableItem{
        ID: ID,
        Amount: amount,
    }
    err := db.Clauses(clause.OnConflict{
        DoUpdates: clause.Assignments(map[string]interface{}{"amount": item.Amount}),
    }).Create(item).Error
    if err != nil {
        return err
    }

    return nil
}

#golang #gorm







Related Posts

關於 React 小書:React 評論功能(四):localStorage、命名與方法擺放順序

關於 React 小書:React 評論功能(四):localStorage、命名與方法擺放順序

用 Python 自學資料科學與機器學習入門實戰:Numpy 基礎入門

用 Python 自學資料科學與機器學習入門實戰:Numpy 基礎入門

簡明 SQL 資料庫語法入門教學

簡明 SQL 資料庫語法入門教學


Comments